<?php

namespace App\Http\Controllers\group;

use App\Constant\Enum;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserWalletActive;
use App\Models\UserWithdraw;
use App\Services\Withdraw\GroupWithdrawService;
use Illuminate\Http\Request;

class MineController extends BaseController
{
    public function withdraws(Request $request)
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        $list = UserWithdraw::query()
            ->select(['id', 'money', 'applied_at', 'audited_at', 'status', 'remark'])
            ->where('wallet_type', Enum::WALLET_TYPE_COMMISSION)
            ->where([
                'user_id' => $user->getAttribute('id')
            ])
            ->orderBy('created_at', 'desc')
            ->get();

        $exchangeRate = Setting::get('exchange_rate');
        // 已提现金额
        $coins = UserWalletActive::query()
            ->where([
                'user_id' => $user->getAttribute('id'),
                'action' => Enum::WALLET_ACTIVE_ACTION_OUTCOME,
                'wallet_type' => Enum::WALLET_TYPE_COMMISSION,
                'status' => Enum::ADREWARD_DETAIL_COLLECT_STATUS_APPROVED,
            ])
            ->sum('coins');
        $outcomes = sprintf("%.2f", $coins / $exchangeRate);


        return $this->success([
            'outcomes' => $outcomes,
            'list' => $list,
        ]);
    }

    public function apply(Request $request)
    {
        try {
            $withdraw = GroupWithdrawService::apply(auth('jwt')->user());

            return $this->success($withdraw, '提现申请已发起');
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function applyReturn(Request $request){

        try {
            $withdraw = GroupWithdrawService::applyReturn(auth('jwt')->user());

            return $this->success($withdraw, '提现申请已发起');
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}
